<template>
    <ItemFilter :type="type" :title="title" :options="options" :modelValue="modelValue"
        @update:modelValue="handleModelValueUpdate" @filter-change="handleFilterChange"
        @display-change="handleDisplayChange" />
</template>

<script lang="ts" setup>
import ItemFilter from '../ItemFilter/index.vue';
import type { FilterType, FilterOption, FilterItem } from '../ItemFilter/types';

interface Props {
    type: FilterType;
    title: string;
    options: FilterOption[];
    modelValue: FilterItem[];
}

const props = defineProps<Props>();
const emit = defineEmits(['update:modelValue']);

const handleModelValueUpdate = (items: FilterItem[]) => {
    emit('update:modelValue', items);
};

const handleFilterChange = (checked: boolean, value: string, label: string) => {
    const newModelValue = [...props.modelValue];
    const itemIndex = newModelValue.findIndex(item => item.value === value && item.label === label);

    if (itemIndex !== -1) {
        newModelValue[itemIndex] = {
            ...newModelValue[itemIndex],
            filterEnabled: checked
        };
        emit('update:modelValue', newModelValue);
    }
};

const handleDisplayChange = (checked: boolean, value: string, label: string) => {
    const newModelValue = [...props.modelValue];
    const itemIndex = newModelValue.findIndex(item => item.value === value && item.label === label);

    if (itemIndex !== -1) {
        newModelValue[itemIndex] = {
            ...newModelValue[itemIndex],
            displayEnabled: checked
        };
        emit('update:modelValue', newModelValue);
    }
};
</script>